About the project

I went to the R-courses last fall and even though it was really difficult to me and lot of hard work needed, I really got excited and now Im here again feeling very uncertain but at the same time very motivated to learn. Here is the link to my IODS project in GitHub https://github.com/madmintt/IODS-project


REGRESSION AND MODEL VALIDATION

This week I have learned to draw advanced scatterplots and some new things about the diagnostics of regressionmodel.

## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
## 
## Attaching package: 'GGally'
## The following object is masked from 'package:dplyr':
## 
##     nasa
learning2014 <-read.csv("create_learning2014.csv", TRUE, ",")
summary(learning2014)
##       X.3              X.2              X.1               X         
##  Min.   :  1.00   Min.   :  1.00   Min.   :  1.00   Min.   :  1.00  
##  1st Qu.: 42.25   1st Qu.: 42.25   1st Qu.: 42.25   1st Qu.: 42.25  
##  Median : 83.50   Median : 83.50   Median : 83.50   Median : 83.50  
##  Mean   : 83.50   Mean   : 83.50   Mean   : 83.50   Mean   : 83.50  
##  3rd Qu.:124.75   3rd Qu.:124.75   3rd Qu.:124.75   3rd Qu.:124.75  
##  Max.   :166.00   Max.   :166.00   Max.   :166.00   Max.   :166.00  
##  gender       Age           Attitude          deep            stra      
##  F:110   Min.   :17.00   Min.   :1.400   Min.   :1.583   Min.   :1.250  
##  M: 56   1st Qu.:21.00   1st Qu.:2.600   1st Qu.:3.333   1st Qu.:2.625  
##          Median :22.00   Median :3.200   Median :3.667   Median :3.188  
##          Mean   :25.51   Mean   :3.143   Mean   :3.680   Mean   :3.121  
##          3rd Qu.:27.00   3rd Qu.:3.700   3rd Qu.:4.083   3rd Qu.:3.625  
##          Max.   :55.00   Max.   :5.000   Max.   :4.917   Max.   :5.000  
##       surf           Points     
##  Min.   :1.583   Min.   : 7.00  
##  1st Qu.:2.417   1st Qu.:19.00  
##  Median :2.833   Median :23.00  
##  Mean   :2.787   Mean   :22.72  
##  3rd Qu.:3.167   3rd Qu.:27.75  
##  Max.   :4.333   Max.   :33.00

This data includes 166 observations and seven variables, witch are gender, age, attitude (towards statistics) and three different studyingstrategies -or skills; deep, surface and strategic. The data includes also the exam points -variable, whitch we consider here the indicator of learning statistics.

VISUALIZING THE DATA

Plot matrix of the variables

visual_d <- ggpairs(learning2014, mapping = aes(col = gender, alpha = 0.3), lower = list(combo = wrap("facethist", bins = 20)))
visual_d

pa <- ggplot(learning2014, aes(x = Attitude, y = Points, col = gender))
pat <- pa + geom_point()
patt <-pat + geom_smooth(method = "lm")
patti <-patt + ggtitle("Attitude vs. points")
patti

There seems to be a positive connection between attitude and points.

pd <- ggplot(learning2014, aes(x = deep, y = Points, col = gender))
pde <- pd + geom_point()
pdee <- pde + geom_smooth(method = "lm")
pdeep <- pdee + ggtitle("Deep vs. points")
pdeep

There seems to be absolutely no connection between deep and points.

pst <- ggplot(learning2014, aes(x = stra, y = Points, col = gender))
pstr <- pst + geom_point()
pstra <- pstr + geom_smooth(method = "lm")
pstrat <- pstra + ggtitle("Strategic vs. points")
pstrat

There might be a small positive connection between strategic and points.

psu <- ggplot(learning2014, aes(x = surf, y = Points, col = gender))
psur <- psu + geom_point()
psurf <- psur + geom_smooth(method = "lm")
psurfa <- psurf + ggtitle("Surface vs. points")
psurfa

There could be a small negative connection between surface and points.

ika <- ggplot(learning2014, aes(x = Age, y = Points, col = gender))
ikak <- ika + geom_point()
ikak <- ika + geom_smooth(method = "lm")
ikaka <- ikak + ggtitle("Age vs. points")
ikaka

According to this it seems like age has something to do with the points in the malegroup.

my_regressionmodel <- lm(formula = Points ~ Attitude, data = learning2014)
summary(my_regressionmodel)
## 
## Call:
## lm(formula = Points ~ Attitude, data = learning2014)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -16.9763  -3.2119   0.4339   4.1534  10.6645 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  11.6372     1.8303   6.358 1.95e-09 ***
## Attitude      3.5255     0.5674   6.214 4.12e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared:  0.1906, Adjusted R-squared:  0.1856 
## F-statistic: 38.61 on 1 and 164 DF,  p-value: 4.119e-09

I did the regression analysis first with having attitude, strategic and surface-learning as explanatory variables, because they seemed to be the three most potential explanatories when looking at the plots. However, the regression analysis showed, that no other variables but attitude are explaining the exampoints with statistical significance, so I only left that in the final model. So the interpretation is that when attitude increases one unit, the exampoints increases 3.5 in average. The multiple R-square is 0.1906 whitch means that the model explains 19 % of the variance of the exampoints in this case.

Diagnostic plots

Every statistical model includes several assumptions. The linear regresssion model assumes first of all that the errors of the model are normally distributed. Another assumption of linear regression model is that the errors have a constant variance and that they are not dependent of the explanatory variables. By making diagnostic plots we can see if theese assumptions come true in our model.

par(mfrow = c(2,2))
plot(my_regressionmodel, which = c(1, 2, 5))

By looking at the diagnostic plot of Residuals vs. Fitted values, we can see, that the plots form no pattern, whitch means that the errors do not depend on the explanatory variable,so no problem in there. The QQplot shows a nice fit with the line interpreting that the errors are normally distributed. The value of leverage is very low 0.04, which means that there are no observations with unusual leverage.


LOGISTICAL REGRESSION

library(ggplot2)
library(dplyr)
library(tidyr)
library(boot)
alc <- read.csv("create_alc.csv", TRUE, ",")
summary(alc)
##        X          school   sex          age        address famsize  
##  Min.   :  1.00   GP:342   F:198   Min.   :15.00   R: 81   GT3:278  
##  1st Qu.: 96.25   MS: 40   M:184   1st Qu.:16.00   U:301   LE3:104  
##  Median :191.50                    Median :17.00                    
##  Mean   :191.50                    Mean   :16.59                    
##  3rd Qu.:286.75                    3rd Qu.:17.00                    
##  Max.   :382.00                    Max.   :22.00                    
##  Pstatus      Medu            Fedu             Mjob           Fjob    
##  A: 38   Min.   :0.000   Min.   :0.000   at_home : 53   at_home : 16  
##  T:344   1st Qu.:2.000   1st Qu.:2.000   health  : 33   health  : 17  
##          Median :3.000   Median :3.000   other   :138   other   :211  
##          Mean   :2.806   Mean   :2.565   services: 96   services:107  
##          3rd Qu.:4.000   3rd Qu.:4.000   teacher : 62   teacher : 31  
##          Max.   :4.000   Max.   :4.000                                
##         reason    nursery   internet    guardian     traveltime   
##  course    :140   no : 72   no : 58   father: 91   Min.   :1.000  
##  home      :110   yes:310   yes:324   mother:275   1st Qu.:1.000  
##  other     : 34                       other : 16   Median :1.000  
##  reputation: 98                                    Mean   :1.448  
##                                                    3rd Qu.:2.000  
##                                                    Max.   :4.000  
##    studytime        failures      schoolsup famsup     paid     activities
##  Min.   :1.000   Min.   :0.0000   no :331   no :144   no :205   no :181   
##  1st Qu.:1.000   1st Qu.:0.0000   yes: 51   yes:238   yes:177   yes:201   
##  Median :2.000   Median :0.0000                                           
##  Mean   :2.037   Mean   :0.2016                                           
##  3rd Qu.:2.000   3rd Qu.:0.0000                                           
##  Max.   :4.000   Max.   :3.0000                                           
##  higher    romantic      famrel         freetime        goout      
##  no : 18   no :261   Min.   :1.000   Min.   :1.00   Min.   :1.000  
##  yes:364   yes:121   1st Qu.:4.000   1st Qu.:3.00   1st Qu.:2.000  
##                      Median :4.000   Median :3.00   Median :3.000  
##                      Mean   :3.937   Mean   :3.22   Mean   :3.113  
##                      3rd Qu.:5.000   3rd Qu.:4.00   3rd Qu.:4.000  
##                      Max.   :5.000   Max.   :5.00   Max.   :5.000  
##       Dalc            Walc           health         absences   
##  Min.   :1.000   Min.   :1.000   Min.   :1.000   Min.   : 0.0  
##  1st Qu.:1.000   1st Qu.:1.000   1st Qu.:3.000   1st Qu.: 1.0  
##  Median :1.000   Median :2.000   Median :4.000   Median : 3.0  
##  Mean   :1.482   Mean   :2.296   Mean   :3.573   Mean   : 4.5  
##  3rd Qu.:2.000   3rd Qu.:3.000   3rd Qu.:5.000   3rd Qu.: 6.0  
##  Max.   :5.000   Max.   :5.000   Max.   :5.000   Max.   :45.0  
##        G1              G2              G3           alc_use     
##  Min.   : 2.00   Min.   : 4.00   Min.   : 0.00   Min.   :1.000  
##  1st Qu.:10.00   1st Qu.:10.00   1st Qu.:10.00   1st Qu.:1.000  
##  Median :12.00   Median :12.00   Median :12.00   Median :1.500  
##  Mean   :11.49   Mean   :11.47   Mean   :11.46   Mean   :1.889  
##  3rd Qu.:14.00   3rd Qu.:14.00   3rd Qu.:14.00   3rd Qu.:2.500  
##  Max.   :18.00   Max.   :18.00   Max.   :18.00   Max.   :5.000  
##   high_use      
##  Mode :logical  
##  FALSE:268      
##  TRUE :114      
##                 
##                 
## 
colnames(alc)
##  [1] "X"          "school"     "sex"        "age"        "address"   
##  [6] "famsize"    "Pstatus"    "Medu"       "Fedu"       "Mjob"      
## [11] "Fjob"       "reason"     "nursery"    "internet"   "guardian"  
## [16] "traveltime" "studytime"  "failures"   "schoolsup"  "famsup"    
## [21] "paid"       "activities" "higher"     "romantic"   "famrel"    
## [26] "freetime"   "goout"      "Dalc"       "Walc"       "health"    
## [31] "absences"   "G1"         "G2"         "G3"         "alc_use"   
## [36] "high_use"
gather(alc) %>% glimpse
## Warning: attributes are not identical across measure variables;
## they will be dropped
## Observations: 13,752
## Variables: 2
## $ key   <chr> "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "X", "...
## $ value <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11",...
alc1 <- gather(alc) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free")
## Warning: attributes are not identical across measure variables;
## they will be dropped
alc1 + geom_bar()

This data approach student achievement in secondary education of two Portuguese schools and the variables include student grades, demographic, social and school related features. In my analysis here my task is to study witch variables affect students consumption of alcohol and predict it. My hypothesis is that studytime relates to alcohol consumption so that the more you drink the less time you study. Alcohol consumption could also have something to do with failures and absences. My guess is also that bad familyrelations could encrease alcohol consumption.

Barplot of alcohol consumption by sex

g1 <- ggplot(data = alc, aes(x = high_use, fill = sex))
g1 + geom_bar()

Ggplot of alcohol consumption

g2 <- ggplot(data = alc, aes(x = high_use))
g3 <- g2 + geom_bar()
g4 <- g3 + facet_wrap("sex")
g4

The distribution of familyrelations and alcohol consumption

g1 <- ggplot(alc, aes(x = high_use, y = famrel,col = sex))
g1 + geom_boxplot() + ylab("famrel")

alc %>% group_by(sex, high_use, famrel) %>% summarise(count = n())
## # A tibble: 19 x 4
## # Groups:   sex, high_use [4]
##    sex   high_use famrel count
##    <fct> <lgl>     <int> <int>
##  1 F     FALSE         1     5
##  2 F     FALSE         2     7
##  3 F     FALSE         3    24
##  4 F     FALSE         4    81
##  5 F     FALSE         5    39
##  6 F     TRUE          2     3
##  7 F     TRUE          3    12
##  8 F     TRUE          4    19
##  9 F     TRUE          5     8
## 10 M     FALSE         1     1
## 11 M     FALSE         2     3
## 12 M     FALSE         3    15
## 13 M     FALSE         4    54
## 14 M     FALSE         5    39
## 15 M     TRUE          1     2
## 16 M     TRUE          2     6
## 17 M     TRUE          3    13
## 18 M     TRUE          4    35
## 19 M     TRUE          5    16

By looking at the barplots it seems like there could be a relation between familyrelations and high use of alcohol; the familyrelations in the non-high use are higher. Same kind of evaluations seems possible when looking at the groopingtable as well.

The distributions of studytime and alcohol use

g1 <- ggplot(alc, aes(x = high_use, y = studytime,col = sex))
g1 + geom_boxplot() + ylab("studytime")

alc %>% group_by(sex, high_use, studytime) %>% summarise(count = n())
## # A tibble: 16 x 4
## # Groups:   sex, high_use [4]
##    sex   high_use studytime count
##    <fct> <lgl>        <int> <int>
##  1 F     FALSE            1    18
##  2 F     FALSE            2    83
##  3 F     FALSE            3    39
##  4 F     FALSE            4    16
##  5 F     TRUE             1     9
##  6 F     TRUE             2    25
##  7 F     TRUE             3     7
##  8 F     TRUE             4     1
##  9 M     FALSE            1    40
## 10 M     FALSE            2    52
## 11 M     FALSE            3    13
## 12 M     FALSE            4     7
## 13 M     TRUE             1    33
## 14 M     TRUE             2    35
## 15 M     TRUE             3     1
## 16 M     TRUE             4     3

Studytime could also be connected to high use of alcohol, at least in femalegroups.

The distributions of failures and alcohol use

g1 <- ggplot(alc, aes(x = high_use, y = failures,col = sex))
g1 + geom_boxplot() + ylab("failures")

alc %>% group_by(sex, high_use, failures) %>% summarise(count = n())
## # A tibble: 15 x 4
## # Groups:   sex, high_use [4]
##    sex   high_use failures count
##    <fct> <lgl>       <int> <int>
##  1 F     FALSE           0   143
##  2 F     FALSE           1     8
##  3 F     FALSE           2     5
##  4 F     TRUE            0    33
##  5 F     TRUE            1     7
##  6 F     TRUE            2     1
##  7 F     TRUE            3     1
##  8 M     FALSE           0   101
##  9 M     FALSE           1     4
## 10 M     FALSE           2     5
## 11 M     FALSE           3     2
## 12 M     TRUE            0    57
## 13 M     TRUE            1     5
## 14 M     TRUE            2     8
## 15 M     TRUE            3     2

What it comes to failures, the hypothesis may not be true; the distributions are looking quite the same in both high-drinkers and those who are not drinking too much. When looking at the table, there are 144 heavy drinkers with zero failiors, but in the other groub the numerus is 90, witch is quite high as well.

The distributions of absences and alcohol use

g1 <- ggplot(alc, aes(x = high_use, y = absences,col = sex))
g1 + geom_boxplot() + ylab("absences")

alc %>% group_by(sex, high_use, absences) %>% summarise(count = n())
## # A tibble: 66 x 4
## # Groups:   sex, high_use [4]
##    sex   high_use absences count
##    <fct> <lgl>       <int> <int>
##  1 F     FALSE           0    28
##  2 F     FALSE           1    17
##  3 F     FALSE           2    32
##  4 F     FALSE           3    15
##  5 F     FALSE           4    11
##  6 F     FALSE           5    10
##  7 F     FALSE           6     9
##  8 F     FALSE           7     7
##  9 F     FALSE           8     9
## 10 F     FALSE           9     4
## # ... with 56 more rows

The number of absences seems to be higher in the heavy drinking group.

A logistical regression model

Mymodel <- glm(high_use ~ failures + absences + famrel + studytime + sex, data = alc, family = "binomial")
summary(Mymodel)
## 
## Call:
## glm(formula = high_use ~ failures + absences + famrel + studytime + 
##     sex, family = "binomial", data = alc)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.0557  -0.8196  -0.5880   1.0121   2.1090  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -0.08166    0.64708  -0.126 0.899579    
## failures     0.33723    0.19336   1.744 0.081155 .  
## absences     0.08492    0.02253   3.769 0.000164 ***
## famrel      -0.27215    0.12898  -2.110 0.034855 *  
## studytime   -0.33349    0.16253  -2.052 0.040186 *  
## sexM         0.85149    0.25493   3.340 0.000837 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 465.68  on 381  degrees of freedom
## Residual deviance: 415.39  on 376  degrees of freedom
## AIC: 427.39
## 
## Number of Fisher Scoring iterations: 4
coef(Mymodel)
## (Intercept)    failures    absences      famrel   studytime        sexM 
## -0.08165709  0.33722680  0.08491968 -0.27215425 -0.33349374  0.85149451
OR <- coef(Mymodel) %>% exp
CI <- confint(Mymodel) %>% exp
## Waiting for profiling to be done...
cbind(OR, CI)
##                    OR     2.5 %    97.5 %
## (Intercept) 0.9215879 0.2570726 3.2760808
## failures    1.4010568 0.9596267 2.0600366
## absences    1.0886296 1.0436932 1.1405269
## famrel      0.7617368 0.5907516 0.9813904
## studytime   0.7164164 0.5166676 0.9790799
## sexM        2.3431461 1.4282690 3.8884700

Acording to this model all explanatory variables with the exception of failures, explain alcohol consumption of the students with statistical significance. Even so, failures OD is 1.40 and the interval of confidence is between 0.96 and 2.06 so I dont know how to interpret this when OD over 1 means positive association with high drinking and it would be 1.4 times likely to be a heavy drinker when having one unit more absences.So now I really dont know if I should leave failures from my prediction. Another predictor seems to be absences with oddsratio 1.09, witch means that those with more absences are 1.9 times more likely to be high users. The confidence interval is between 1.04 and 1.14 witch is the narrowest in this model. The OR is over 1 in any case, witch means that absences are positively associated with heavy drinking. Sex seems to be a good explainer so that males are 2.34 times more likely (than females) to be high users of alcohol. Familyrelations and sudytime has weaker OR and the maximum in the interval of confidence is below 1 witch is logical since the better familyrelations you have and the more you study the lower odds for you to be a high user of alcohol.

Prediction

Mymodel <- glm(high_use ~ absences + sex + famrel + studytime, data = alc, family = "binomial")
probabilities <- predict(Mymodel, type = "response")
alc <- mutate(alc, probability = probabilities)
alc <- mutate(alc, prediction = probabilities > 0.5)
table(high_use = alc$high_use, prediction = probabilities > 0.5)
##         prediction
## high_use FALSE TRUE
##    FALSE   250   18
##    TRUE     86   28
g <- ggplot(alc, aes(x = probability, y = high_use, col = prediction))
g + geom_point()

table(high_use = alc$high_use, prediction = alc$prediction) %>% prop.table() %>% addmargins()
##         prediction
## high_use      FALSE       TRUE        Sum
##    FALSE 0.65445026 0.04712042 0.70157068
##    TRUE  0.22513089 0.07329843 0.29842932
##    Sum   0.87958115 0.12041885 1.00000000
loss_func <- function(class, prob) {
  n_wrong <- abs(class - prob) > 0.5
  mean(n_wrong)
}
loss_func(class = alc$high_use, prob = alc$probability)
## [1] 0.2722513

The propability that the model predicts right FALSE is 0.65 and wronng FALSE 0.05. The propability that the model predicts right TRUE is 0.07 and wrong TRUE 0.23. The training error is 0.27.

cv <- cv.glm(data = alc, cost = loss_func, glmfit = Mymodel, K = 10)
cv$delta
## [1] 0.2774869 0.2814547

The training error is just a little bit bigger than in the model introduced in Datacamp.

Super-bonus

vari27 <- 0.194
vari26 <- 0.199
vari25 <- 0.196
vari24 <- 0.188
vari23 <- 0.191
vari22 <- 0.188
vari21 <- 0.199
vari20 <- 0.196
vari19 <- 0.196
vari18 <- 0.191
vari17 <- 0.196
vari16 <- 0.191
vari15 <- 0.194
vari14 <- 0.188
vari13 <- 0.188
vari12 <- 0.191
vari11 <- 0.196
vari10 <- 0.215
vari9 <- 0.220
vari8 <- 0.223
vari7 <- 0.217
vari6 <- 0.225
vari5 <- 0.262
vari4 <- 0.272
vari3 <- 0.257
vari2 <- 0.283
vari1 <- 0.288

I just put all the variables in the model and started to remove the variables one of a time and then checked out the training error. THe trend here is that less variables, the bigger penalty.

variab <- c(vari1, vari2, vari3, vari4, vari5, vari6, vari7, vari8, vari9, vari10, vari11, vari12, vari13, vari14, vari15, vari16, vari17, vari18, vari19, vari20, vari21, vari22, vari23, vari24, vari25, vari26, vari27)
variables <- c( 1 : 27)
plot(variab, variables)


CLUSTERING AND CLASSIFICATION

library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
data("Boston")
library("ggplot2")
library("dplyr")
library("GGally")
library("corrplot")
## corrplot 0.84 loaded
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(Boston)
## [1] 506  14
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00

The Boston data includes variables describing Boston such as for example what is the degree of criminality, the distribution of age in Boston, lower status of population or pupil-teacher ratio in town. The data has 506 observations and 14 variables.

Bosgraph <- ggpairs(Boston, mapping = aes(alpha = 0.3), lower = list(combo = wrap("facethist", bins = 20)))
Bosgraph

cor(Boston)
##                crim          zn       indus         chas         nox
## crim     1.00000000 -0.20046922  0.40658341 -0.055891582  0.42097171
## zn      -0.20046922  1.00000000 -0.53382819 -0.042696719 -0.51660371
## indus    0.40658341 -0.53382819  1.00000000  0.062938027  0.76365145
## chas    -0.05589158 -0.04269672  0.06293803  1.000000000  0.09120281
## nox      0.42097171 -0.51660371  0.76365145  0.091202807  1.00000000
## rm      -0.21924670  0.31199059 -0.39167585  0.091251225 -0.30218819
## age      0.35273425 -0.56953734  0.64477851  0.086517774  0.73147010
## dis     -0.37967009  0.66440822 -0.70802699 -0.099175780 -0.76923011
## rad      0.62550515 -0.31194783  0.59512927 -0.007368241  0.61144056
## tax      0.58276431 -0.31456332  0.72076018 -0.035586518  0.66802320
## ptratio  0.28994558 -0.39167855  0.38324756 -0.121515174  0.18893268
## black   -0.38506394  0.17552032 -0.35697654  0.048788485 -0.38005064
## lstat    0.45562148 -0.41299457  0.60379972 -0.053929298  0.59087892
## medv    -0.38830461  0.36044534 -0.48372516  0.175260177 -0.42732077
##                  rm         age         dis          rad         tax
## crim    -0.21924670  0.35273425 -0.37967009  0.625505145  0.58276431
## zn       0.31199059 -0.56953734  0.66440822 -0.311947826 -0.31456332
## indus   -0.39167585  0.64477851 -0.70802699  0.595129275  0.72076018
## chas     0.09125123  0.08651777 -0.09917578 -0.007368241 -0.03558652
## nox     -0.30218819  0.73147010 -0.76923011  0.611440563  0.66802320
## rm       1.00000000 -0.24026493  0.20524621 -0.209846668 -0.29204783
## age     -0.24026493  1.00000000 -0.74788054  0.456022452  0.50645559
## dis      0.20524621 -0.74788054  1.00000000 -0.494587930 -0.53443158
## rad     -0.20984667  0.45602245 -0.49458793  1.000000000  0.91022819
## tax     -0.29204783  0.50645559 -0.53443158  0.910228189  1.00000000
## ptratio -0.35550149  0.26151501 -0.23247054  0.464741179  0.46085304
## black    0.12806864 -0.27353398  0.29151167 -0.444412816 -0.44180801
## lstat   -0.61380827  0.60233853 -0.49699583  0.488676335  0.54399341
## medv     0.69535995 -0.37695457  0.24992873 -0.381626231 -0.46853593
##            ptratio       black      lstat       medv
## crim     0.2899456 -0.38506394  0.4556215 -0.3883046
## zn      -0.3916785  0.17552032 -0.4129946  0.3604453
## indus    0.3832476 -0.35697654  0.6037997 -0.4837252
## chas    -0.1215152  0.04878848 -0.0539293  0.1752602
## nox      0.1889327 -0.38005064  0.5908789 -0.4273208
## rm      -0.3555015  0.12806864 -0.6138083  0.6953599
## age      0.2615150 -0.27353398  0.6023385 -0.3769546
## dis     -0.2324705  0.29151167 -0.4969958  0.2499287
## rad      0.4647412 -0.44441282  0.4886763 -0.3816262
## tax      0.4608530 -0.44180801  0.5439934 -0.4685359
## ptratio  1.0000000 -0.17738330  0.3740443 -0.5077867
## black   -0.1773833  1.00000000 -0.3660869  0.3334608
## lstat    0.3740443 -0.36608690  1.0000000 -0.7376627
## medv    -0.5077867  0.33346082 -0.7376627  1.0000000
cor_matrix<-cor(Boston) 
cor_matrix <- cor_matrix %>% round(digits = 2)
corrplot(cor_matrix, method= "circle")

In this correlation matrix we can see all the variables in the Boston data and their between-correlations. The more darker the color, the stronger the correlation. The shades of red describe negative, and the shades of blue positive correlation. The median value of owner-occupied homes has a strong negative correlation with lower status of population.

Standardizing the data and changing the continuous crime rate -variable in to a categorical one

Next the data will be standardized, ie. it will be scaled so that the column means are subtracted from the corresponding columns and then divided the difference with standard deviation.

boston_scaled <- scale(Boston)
summary(boston_scaled)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
class(boston_scaled)
## [1] "matrix"
boston_scaled <- as.data.frame(boston_scaled)
summary(boston_scaled$crim)
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
## -0.419367 -0.410563 -0.390280  0.000000  0.007389  9.924110
bins <- quantile(boston_scaled$crim)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, label= c("low", "med_low", "med_high", "high"))
table(crime)
## crime
##      low  med_low med_high     high 
##      127      126      126      127
boston_scaled <- dplyr::select(boston_scaled, -crim)
boston_scaled <- data.frame(boston_scaled, crime)

Splitting the data to train and test sets

n <- nrow(boston_scaled)
ind <- sample(n,  size = n * 0.8)
train <- boston_scaled[ind,]
test <- boston_scaled[-ind,]
correct_classes <- test$crime
test <- dplyr::select(test, -crime)

The LDA model

lda.fit <- lda(crime ~ ., data = train)
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2524752 0.2574257 0.2450495 0.2450495 
## 
## Group means:
##                   zn      indus        chas        nox          rm
## low       1.06369310 -0.9783716 -0.07933396 -0.9135729  0.42033731
## med_low  -0.06877583 -0.2852721 -0.08304540 -0.5704280 -0.13928661
## med_high -0.38242941  0.1636528  0.20489520  0.4329879  0.06864948
## high     -0.48724019  1.0149946 -0.07348562  1.0479694 -0.37214118
##                 age        dis        rad        tax     ptratio
## low      -0.9394522  0.9321151 -0.6744874 -0.7249343 -0.43729048
## med_low  -0.3625265  0.3650863 -0.5489875 -0.4749390 -0.08605428
## med_high  0.4757839 -0.3935452 -0.4308390 -0.3388924 -0.39330929
## high      0.8339088 -0.8479259  1.6596029  1.5294129  0.80577843
##                black       lstat        medv
## low       0.38387345 -0.79191617  0.50820958
## med_low   0.34421756 -0.12798218 -0.02165382
## med_high  0.02596325  0.06141285  0.16864353
## high     -0.85153308  0.89730985 -0.76456634
## 
## Coefficients of linear discriminants:
##                  LD1          LD2          LD3
## zn       0.119794642  0.633434396 -0.913707123
## indus    0.055135832 -0.292486511  0.515680032
## chas    -0.017231502  0.010844617  0.005481306
## nox      0.229695799 -0.750742048 -1.301856239
## rm       0.021115768  0.008407438 -0.094747201
## age      0.279772086 -0.436883239 -0.261737559
## dis     -0.152929939 -0.301537656  0.163741351
## rad      3.670164754  0.849467899 -0.050775720
## tax     -0.010186067  0.137922525  0.448772408
## ptratio  0.150775335  0.009661024 -0.281587785
## black   -0.149088142  0.055343724  0.216445329
## lstat    0.090199748 -0.224988187  0.376666163
## medv     0.004867651 -0.508151854 -0.223352108
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9509 0.0376 0.0115
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}
classes <- as.numeric(train$crime)
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 1)

lda.pred <- predict(lda.fit, newdata = test)
table(correct = correct_classes, predicted = lda.pred$class)
##           predicted
## correct    low med_low med_high high
##   low        9      14        2    0
##   med_low    2      16        4    0
##   med_high   0       9       16    2
##   high       0       0        1   27

Here we can see that predicting is quite good since the rates are highest in the groups witch are correctly predicted and no radical errors exist.

dist_eu <- dist(boston_scaled)
## Warning in dist(boston_scaled): NAs introduced by coercion
summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1394  3.5267  4.9081  4.9394  6.2421 13.0045
dist_man <- dist(boston_scaled, method = "manhattan")
## Warning in dist(boston_scaled, method = "manhattan"): NAs introduced by
## coercion
summary(dist_man)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.2849  8.8386 13.0300 13.8657 18.0953 46.8948
km <-kmeans(Boston, centers = 2)
km$cluster
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   1   1   1   1 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   1   1   1   1   1   1   1   2   2   2   2   2   2   2   2   2   2   2 
## 505 506 
##   2   2
pairs(boston_scaled[1:5], col = km$cluster)

pairs(boston_scaled[6:10], col = km$cluster)

pairs(boston_scaled[11:14], col = km$cluster)

set.seed(123)
k_max <- (k_max = 10)
twcss <- sapply(1:k_max, function(k){kmeans(Boston, k)$tot.withinss})
qplot(x = 1:k_max, y = twcss, geom = 'line')

I tried the model with 5,4,3 and 2 clusters and my interpretation when viewing the plots is that 3 is best but when calculating WCSS it seems that 2 clusters seems to be better choice. Anyhow variables tax (full-value property-tax rate per $10,000), rad (index of accessibility to radial highways) and some of the classes of crime seems to set clearly in clusters in any case.

Bonus

Bclust <-kmeans(Boston, centers = 3)
Bclust$cluster
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   1   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   3   3   1   1   1   1   1   1   3   3   3   3   3   3   3   3   3   3 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   3   3   3   3   3   3   3   3   3   3   1   1   1   1   1   1   1   1 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   1   1   1   1   1   1   1   1   1   1   1   1   3   3   3   3   3   3 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   3   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   1   1   1   1   1   1   1   1   1   1   3   3   3   3   3   3   3   3 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   3   3   3   3   3   3   3   1   1   1   1   1   1   3   3   3   3   3 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   3   1   1   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   3   3   3   3   3   3   3   3   3   3   1   1   1   3   3   3   3   3 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   3   3   3   3   1   1   1   3   3   3   3   3   3   3   3   3   3   3 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   1   1   1   1   1   3   3   3   3   1   1   3   3   3   2   2   2   2 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   2   2   2   2   2   2   2   1   1   1   1   1   1   1   1   3   3   3 
## 505 506 
##   3   3
pairs(boston_scaled[1:5], col = Bclust$cluster)

pairs(boston_scaled[6:10], col = Bclust$cluster)

pairs(boston_scaled[11:14], col = Bclust$cluster)

lda.fit <- lda(Bclust$cluster ~ ., data = boston_scaled)
lda.fit
## Call:
## lda(Bclust$cluster ~ ., data = boston_scaled)
## 
## Prior probabilities of groups:
##         1         2         3 
## 0.1996047 0.2707510 0.5296443 
## 
## Group means:
##            zn      indus          chas        nox         rm        age
## 1 -0.07332724  0.2818828  0.0005392655  0.2816899 -0.1453417  0.1822823
## 2 -0.48724019  1.0662784 -0.0424254043  0.9959393 -0.3962652  0.7599946
## 3  0.27670879 -0.6513071  0.0214843827 -0.6152775  0.2573427 -0.4572006
##          dis        rad         tax    ptratio       black       lstat
## 1 -0.2378455 -0.5418150 -0.01444889 -0.3768823  0.07010933  0.01371321
## 2 -0.8265965  1.5757732  1.53915759  0.8040926 -0.71893398  0.84321670
## 3  0.5121870 -0.6013344 -0.78136288 -0.2690134  0.34109296 -0.43621538
##          medv crimemed_low crimemed_high  crimehigh
## 1 -0.03812375   0.32673267    0.46534653 0.00990099
## 2 -0.68070813   0.03649635    0.04379562 0.91970803
## 3  0.36234147   0.32835821    0.27238806 0.00000000
## 
## Coefficients of linear discriminants:
##                       LD1          LD2
## zn             0.05280738 -0.014188634
## indus          0.52954210  0.136232438
## chas          -0.03744336  0.041429998
## nox            0.20190265 -0.583371775
## rm             0.02768863  0.117101924
## age           -0.01312130  0.006188618
## dis           -0.36742893  0.203235111
## rad            2.17313453  2.225891425
## tax            5.27359727 -2.772125460
## ptratio        0.14183368  0.150571551
## black         -0.04900742  0.092304730
## lstat          0.19460083  0.100047863
## medv           0.32392299 -0.139204299
## crimemed_low  -0.95555999 -0.081053964
## crimemed_high -2.22131989  0.172165534
## crimehigh     -0.91590244  2.292286225
## 
## Proportion of trace:
##    LD1    LD2 
## 0.9855 0.0145
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}
classes <- as.numeric(Bclust$cluster)
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 1)

Here we can see that the most influencial linear separatorvariables for the clusters are crimerates, rad and tax. LD1 explains 99% of the between group variance.

Superbonus

lda.fit <- lda(crime ~ ., data = train)
model_predictors <- dplyr::select(train, -crime)
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
library("plotly")
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = train$crime)
Bclust <-kmeans(Boston, centers = 3)
lda.fit <- lda(Bclust$cluster ~ ., data = boston_scaled)
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = Bclust)

DIMENSION REDUCTION TECHNIQUES

library("stringr")
library(GGally)
library(dplyr)
library(corrplot)
library(ggplot2)
library(tidyr)
library("FactoMineR")
human_ <- read.csv("create_human_.csv", TRUE, ",")
str(human_)
## 'data.frame':    155 obs. of  9 variables:
##  $ X        : Factor w/ 155 levels "Afghanistan",..: 105 6 134 41 101 54 67 149 28 102 ...
##  $ labRatio : num  0.891 0.819 0.825 0.884 0.829 ...
##  $ edu2Ratio: num  0.993 1.003 1.017 1.012 1.032 ...
##  $ LifeExp  : num  81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
##  $ ExpEdu   : num  17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
##  $ GNI      : int  64992 42261 56431 44025 45435 43919 39568 52947 42155 32689 ...
##  $ Matmort  : int  4 6 6 5 6 7 9 28 11 8 ...
##  $ AdolBR   : num  7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
##  $ ParlPres : num  39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
dim(human_)
## [1] 155   9
summary(human_)
##            X          labRatio        edu2Ratio         LifeExp     
##  Afghanistan:  1   Min.   :0.1857   Min.   :0.6681   Min.   :49.00  
##  Albania    :  1   1st Qu.:0.5984   1st Qu.:1.0032   1st Qu.:66.30  
##  Algeria    :  1   Median :0.7535   Median :1.0667   Median :74.20  
##  Argentina  :  1   Mean   :0.7074   Mean   :1.3523   Mean   :71.65  
##  Armenia    :  1   3rd Qu.:0.8535   3rd Qu.:1.3766   3rd Qu.:77.25  
##  Australia  :  1   Max.   :1.0380   Max.   :5.8235   Max.   :83.50  
##  (Other)    :149                                                    
##      ExpEdu           GNI            Matmort           AdolBR      
##  Min.   : 5.40   Min.   :   581   Min.   :   1.0   Min.   :  0.60  
##  1st Qu.:11.25   1st Qu.:  4198   1st Qu.:  11.5   1st Qu.: 12.65  
##  Median :13.50   Median : 12040   Median :  49.0   Median : 33.60  
##  Mean   :13.18   Mean   : 17628   Mean   : 149.1   Mean   : 47.16  
##  3rd Qu.:15.20   3rd Qu.: 24512   3rd Qu.: 190.0   3rd Qu.: 71.95  
##  Max.   :20.20   Max.   :123124   Max.   :1100.0   Max.   :204.80  
##                                                                    
##     ParlPres    
##  Min.   : 0.00  
##  1st Qu.:12.40  
##  Median :19.30  
##  Mean   :20.91  
##  3rd Qu.:27.95  
##  Max.   :57.50  
## 
rownames(human_) <- human_$X
human_ <- select(human_, -X)

Visualizing the data

ggpairs(human_)

cor(human_)%>%corrplot

This data is a joined data set, witch includes variables from HDI (Human development index) and GII (Gender inequality index). The HDI measures human development by three dimensions; Health, learning/education and standard of living. The variables of GII data measures the inequality between genders giving numbers for example the differences in empowerment, health and labour force. This combined dataset has 195 observations and 19 variables. When looking at the distributions of the variables in this data, we can see that non of the variables really seems to be normally distributed. By just looking at the picture maybe the womens participation in parliament and expected years of education could be normal, other distributions seems to be clearly skew. What comes to correlations between the variables, almost all the variables seems to have a strong connection between, except for womens participation in parliament witch seems to have smaller correlation with other variables in the data. We`ll see how the correlations will change when the amount of women will increace in parliaments hopefully in the future ;) No correlation seems to be between the ratio of labour force and the ratio of secondary education between males and females.

Principal components analysis with scaled and notscaled data

pca_human <- prcomp(human_)
biplot(pca_human, choices = 1:2,cex = c(0.5, 1),  col = c("grey40", "deeppink2"))
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped

human_std <- scale(human_)
pca_human <- prcomp(human_std)
biplot(pca_human, choices = 1:2, cex = c(0.5, 1), col = c("grey40", "deeppink2"))

The data is the same in both cases of course, but with unscaled data PCA is sensitive to the relative scaling of the variance of the original variables,so the biplots of PCA looks quite different with scaled and unscaled data. With unscaaled data the PCA has all the other variables in one arrow pointing to PC1 dimension and demonstrating a perfect correlation between them as well as with PC1. This is not surprizing since the correlation between the variables is overall strong and with unscaled data the PCA has difficulties to differ the dimensions. Only the variable GNI has no arrow. Whit the scaled data we can see that the mortality rate of birthgiven mothers and adolescents birth rate has a strong connection with each other, witch was seen in the correlation matrix as well. Mothers mortality and adolescents birth rate seems to set nicely to dimension PC1. Expected years of education, national income per capita, life expectancy and the secondary education ratio between females and males seems to set also to dimension PC1 but not having correlation with mothers mortality rate and adolescens birth rate. The PC1 dimension seems to represent the health and knowledge -part of human development. On the second dimension in PCA there is women participation in parliament and the labor force ratio between females and males, witch has a between correlation as well. This we can consider as the empowerment -part of human development.

MCA

data("tea")
keep_columns <- c("Tea", "How", "how", "sugar", "where", "lunch")
tea_time <- select(tea,one_of(keep_columns) )
dim(tea_time)
## [1] 300   6
str(tea_time)
## 'data.frame':    300 obs. of  6 variables:
##  $ Tea  : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
##  $ How  : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
##  $ how  : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
##  $ sugar: Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
##  $ where: Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
##  $ lunch: Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
gather(tea_time) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
## Warning: attributes are not identical across measure variables;
## they will be dropped

The tea data is about the tea consumption and the relating culture or habits. Here we look at 6 factor variables and the data consist of 300 observations.

mca <- MCA(tea_time, graph = FALSE)
summary(mca)
## 
## Call:
## MCA(X = tea_time, graph = FALSE) 
## 
## 
## Eigenvalues
##                        Dim.1   Dim.2   Dim.3   Dim.4   Dim.5   Dim.6
## Variance               0.279   0.261   0.219   0.189   0.177   0.156
## % of var.             15.238  14.232  11.964  10.333   9.667   8.519
## Cumulative % of var.  15.238  29.471  41.435  51.768  61.434  69.953
##                        Dim.7   Dim.8   Dim.9  Dim.10  Dim.11
## Variance               0.144   0.141   0.117   0.087   0.062
## % of var.              7.841   7.705   6.392   4.724   3.385
## Cumulative % of var.  77.794  85.500  91.891  96.615 100.000
## 
## Individuals (the 10 first)
##                       Dim.1    ctr   cos2    Dim.2    ctr   cos2    Dim.3
## 1                  | -0.298  0.106  0.086 | -0.328  0.137  0.105 | -0.327
## 2                  | -0.237  0.067  0.036 | -0.136  0.024  0.012 | -0.695
## 3                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 4                  | -0.530  0.335  0.460 | -0.318  0.129  0.166 |  0.211
## 5                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 6                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 7                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 8                  | -0.237  0.067  0.036 | -0.136  0.024  0.012 | -0.695
## 9                  |  0.143  0.024  0.012 |  0.871  0.969  0.435 | -0.067
## 10                 |  0.476  0.271  0.140 |  0.687  0.604  0.291 | -0.650
##                       ctr   cos2  
## 1                   0.163  0.104 |
## 2                   0.735  0.314 |
## 3                   0.062  0.069 |
## 4                   0.068  0.073 |
## 5                   0.062  0.069 |
## 6                   0.062  0.069 |
## 7                   0.062  0.069 |
## 8                   0.735  0.314 |
## 9                   0.007  0.003 |
## 10                  0.643  0.261 |
## 
## Categories (the 10 first)
##                        Dim.1     ctr    cos2  v.test     Dim.2     ctr
## black              |   0.473   3.288   0.073   4.677 |   0.094   0.139
## Earl Grey          |  -0.264   2.680   0.126  -6.137 |   0.123   0.626
## green              |   0.486   1.547   0.029   2.952 |  -0.933   6.111
## alone              |  -0.018   0.012   0.001  -0.418 |  -0.262   2.841
## lemon              |   0.669   2.938   0.055   4.068 |   0.531   1.979
## milk               |  -0.337   1.420   0.030  -3.002 |   0.272   0.990
## other              |   0.288   0.148   0.003   0.876 |   1.820   6.347
## tea bag            |  -0.608  12.499   0.483 -12.023 |  -0.351   4.459
## tea bag+unpackaged |   0.350   2.289   0.056   4.088 |   1.024  20.968
## unpackaged         |   1.958  27.432   0.523  12.499 |  -1.015   7.898
##                       cos2  v.test     Dim.3     ctr    cos2  v.test  
## black                0.003   0.929 |  -1.081  21.888   0.382 -10.692 |
## Earl Grey            0.027   2.867 |   0.433   9.160   0.338  10.053 |
## green                0.107  -5.669 |  -0.108   0.098   0.001  -0.659 |
## alone                0.127  -6.164 |  -0.113   0.627   0.024  -2.655 |
## lemon                0.035   3.226 |   1.329  14.771   0.218   8.081 |
## milk                 0.020   2.422 |   0.013   0.003   0.000   0.116 |
## other                0.102   5.534 |  -2.524  14.526   0.197  -7.676 |
## tea bag              0.161  -6.941 |  -0.065   0.183   0.006  -1.287 |
## tea bag+unpackaged   0.478  11.956 |   0.019   0.009   0.000   0.226 |
## unpackaged           0.141  -6.482 |   0.257   0.602   0.009   1.640 |
## 
## Categorical variables (eta2)
##                      Dim.1 Dim.2 Dim.3  
## Tea                | 0.126 0.108 0.410 |
## How                | 0.076 0.190 0.394 |
## how                | 0.708 0.522 0.010 |
## sugar              | 0.065 0.001 0.336 |
## where              | 0.702 0.681 0.055 |
## lunch              | 0.000 0.064 0.111 |
plot(mca, invisible=c("ind"), habillage = "quali")

mca <- MCA(tea_time, graph = FALSE)
summary(mca)
## 
## Call:
## MCA(X = tea_time, graph = FALSE) 
## 
## 
## Eigenvalues
##                        Dim.1   Dim.2   Dim.3   Dim.4   Dim.5   Dim.6
## Variance               0.279   0.261   0.219   0.189   0.177   0.156
## % of var.             15.238  14.232  11.964  10.333   9.667   8.519
## Cumulative % of var.  15.238  29.471  41.435  51.768  61.434  69.953
##                        Dim.7   Dim.8   Dim.9  Dim.10  Dim.11
## Variance               0.144   0.141   0.117   0.087   0.062
## % of var.              7.841   7.705   6.392   4.724   3.385
## Cumulative % of var.  77.794  85.500  91.891  96.615 100.000
## 
## Individuals (the 10 first)
##                       Dim.1    ctr   cos2    Dim.2    ctr   cos2    Dim.3
## 1                  | -0.298  0.106  0.086 | -0.328  0.137  0.105 | -0.327
## 2                  | -0.237  0.067  0.036 | -0.136  0.024  0.012 | -0.695
## 3                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 4                  | -0.530  0.335  0.460 | -0.318  0.129  0.166 |  0.211
## 5                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 6                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 7                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 8                  | -0.237  0.067  0.036 | -0.136  0.024  0.012 | -0.695
## 9                  |  0.143  0.024  0.012 |  0.871  0.969  0.435 | -0.067
## 10                 |  0.476  0.271  0.140 |  0.687  0.604  0.291 | -0.650
##                       ctr   cos2  
## 1                   0.163  0.104 |
## 2                   0.735  0.314 |
## 3                   0.062  0.069 |
## 4                   0.068  0.073 |
## 5                   0.062  0.069 |
## 6                   0.062  0.069 |
## 7                   0.062  0.069 |
## 8                   0.735  0.314 |
## 9                   0.007  0.003 |
## 10                  0.643  0.261 |
## 
## Categories (the 10 first)
##                        Dim.1     ctr    cos2  v.test     Dim.2     ctr
## black              |   0.473   3.288   0.073   4.677 |   0.094   0.139
## Earl Grey          |  -0.264   2.680   0.126  -6.137 |   0.123   0.626
## green              |   0.486   1.547   0.029   2.952 |  -0.933   6.111
## alone              |  -0.018   0.012   0.001  -0.418 |  -0.262   2.841
## lemon              |   0.669   2.938   0.055   4.068 |   0.531   1.979
## milk               |  -0.337   1.420   0.030  -3.002 |   0.272   0.990
## other              |   0.288   0.148   0.003   0.876 |   1.820   6.347
## tea bag            |  -0.608  12.499   0.483 -12.023 |  -0.351   4.459
## tea bag+unpackaged |   0.350   2.289   0.056   4.088 |   1.024  20.968
## unpackaged         |   1.958  27.432   0.523  12.499 |  -1.015   7.898
##                       cos2  v.test     Dim.3     ctr    cos2  v.test  
## black                0.003   0.929 |  -1.081  21.888   0.382 -10.692 |
## Earl Grey            0.027   2.867 |   0.433   9.160   0.338  10.053 |
## green                0.107  -5.669 |  -0.108   0.098   0.001  -0.659 |
## alone                0.127  -6.164 |  -0.113   0.627   0.024  -2.655 |
## lemon                0.035   3.226 |   1.329  14.771   0.218   8.081 |
## milk                 0.020   2.422 |   0.013   0.003   0.000   0.116 |
## other                0.102   5.534 |  -2.524  14.526   0.197  -7.676 |
## tea bag              0.161  -6.941 |  -0.065   0.183   0.006  -1.287 |
## tea bag+unpackaged   0.478  11.956 |   0.019   0.009   0.000   0.226 |
## unpackaged           0.141  -6.482 |   0.257   0.602   0.009   1.640 |
## 
## Categorical variables (eta2)
##                      Dim.1 Dim.2 Dim.3  
## Tea                | 0.126 0.108 0.410 |
## How                | 0.076 0.190 0.394 |
## how                | 0.708 0.522 0.010 |
## sugar              | 0.065 0.001 0.336 |
## where              | 0.702 0.681 0.055 |
## lunch              | 0.000 0.064 0.111 |
plot(mca, invisible=c("var"), habillage = "quali")

mca <- MCA(tea_time, graph = FALSE)
summary(mca)
## 
## Call:
## MCA(X = tea_time, graph = FALSE) 
## 
## 
## Eigenvalues
##                        Dim.1   Dim.2   Dim.3   Dim.4   Dim.5   Dim.6
## Variance               0.279   0.261   0.219   0.189   0.177   0.156
## % of var.             15.238  14.232  11.964  10.333   9.667   8.519
## Cumulative % of var.  15.238  29.471  41.435  51.768  61.434  69.953
##                        Dim.7   Dim.8   Dim.9  Dim.10  Dim.11
## Variance               0.144   0.141   0.117   0.087   0.062
## % of var.              7.841   7.705   6.392   4.724   3.385
## Cumulative % of var.  77.794  85.500  91.891  96.615 100.000
## 
## Individuals (the 10 first)
##                       Dim.1    ctr   cos2    Dim.2    ctr   cos2    Dim.3
## 1                  | -0.298  0.106  0.086 | -0.328  0.137  0.105 | -0.327
## 2                  | -0.237  0.067  0.036 | -0.136  0.024  0.012 | -0.695
## 3                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 4                  | -0.530  0.335  0.460 | -0.318  0.129  0.166 |  0.211
## 5                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 6                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 7                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 8                  | -0.237  0.067  0.036 | -0.136  0.024  0.012 | -0.695
## 9                  |  0.143  0.024  0.012 |  0.871  0.969  0.435 | -0.067
## 10                 |  0.476  0.271  0.140 |  0.687  0.604  0.291 | -0.650
##                       ctr   cos2  
## 1                   0.163  0.104 |
## 2                   0.735  0.314 |
## 3                   0.062  0.069 |
## 4                   0.068  0.073 |
## 5                   0.062  0.069 |
## 6                   0.062  0.069 |
## 7                   0.062  0.069 |
## 8                   0.735  0.314 |
## 9                   0.007  0.003 |
## 10                  0.643  0.261 |
## 
## Categories (the 10 first)
##                        Dim.1     ctr    cos2  v.test     Dim.2     ctr
## black              |   0.473   3.288   0.073   4.677 |   0.094   0.139
## Earl Grey          |  -0.264   2.680   0.126  -6.137 |   0.123   0.626
## green              |   0.486   1.547   0.029   2.952 |  -0.933   6.111
## alone              |  -0.018   0.012   0.001  -0.418 |  -0.262   2.841
## lemon              |   0.669   2.938   0.055   4.068 |   0.531   1.979
## milk               |  -0.337   1.420   0.030  -3.002 |   0.272   0.990
## other              |   0.288   0.148   0.003   0.876 |   1.820   6.347
## tea bag            |  -0.608  12.499   0.483 -12.023 |  -0.351   4.459
## tea bag+unpackaged |   0.350   2.289   0.056   4.088 |   1.024  20.968
## unpackaged         |   1.958  27.432   0.523  12.499 |  -1.015   7.898
##                       cos2  v.test     Dim.3     ctr    cos2  v.test  
## black                0.003   0.929 |  -1.081  21.888   0.382 -10.692 |
## Earl Grey            0.027   2.867 |   0.433   9.160   0.338  10.053 |
## green                0.107  -5.669 |  -0.108   0.098   0.001  -0.659 |
## alone                0.127  -6.164 |  -0.113   0.627   0.024  -2.655 |
## lemon                0.035   3.226 |   1.329  14.771   0.218   8.081 |
## milk                 0.020   2.422 |   0.013   0.003   0.000   0.116 |
## other                0.102   5.534 |  -2.524  14.526   0.197  -7.676 |
## tea bag              0.161  -6.941 |  -0.065   0.183   0.006  -1.287 |
## tea bag+unpackaged   0.478  11.956 |   0.019   0.009   0.000   0.226 |
## unpackaged           0.141  -6.482 |   0.257   0.602   0.009   1.640 |
## 
## Categorical variables (eta2)
##                      Dim.1 Dim.2 Dim.3  
## Tea                | 0.126 0.108 0.410 |
## How                | 0.076 0.190 0.394 |
## how                | 0.708 0.522 0.010 |
## sugar              | 0.065 0.001 0.336 |
## where              | 0.702 0.681 0.055 |
## lunch              | 0.000 0.064 0.111 |
plot(mca, habillage = "quali", selectMod = "cos2 20", cex = 0.8)

Here we can see three biplots of MCA, where in one is observations or individuals modelled in dimensions and in the other variables modelled in dimensions. In third picture there are both. Here we can see for example that the unpacked, green tea and tea shop are clearly in the same dimension and milk, Earl gray, tea bag and chain store are in the second. To interpret this more deeply one should understand more the phenomenon and tea drinking human :)


ANALYZING THE LONGITUDINAL DATA

Graphical displays and summary measure approach with the RATS data

library(ggplot2)
library(dplyr)
library(tidyr)
library(lme4)
## Loading required package: Matrix
## 
## Attaching package: 'Matrix'
## The following objects are masked from 'package:tidyr':
## 
##     expand, pack, unpack
RATSL <- read.csv("create_RATSL.csv", TRUE, ",")
glimpse(RATSL)
## Observations: 176
## Variables: 6
## $ X      <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ...
## $ ID     <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ...
## $ Group  <int> 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1...
## $ WD     <fct> WD1, WD1, WD1, WD1, WD1, WD1, WD1, WD1, WD1, WD1, WD1, ...
## $ Weight <int> 240, 225, 245, 260, 255, 260, 275, 245, 410, 405, 445, ...
## $ Time   <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8, 8...
summary(RATSL)
##        X                ID            Group            WD    
##  Min.   :  1.00   Min.   : 1.00   Min.   :1.00   WD1    :16  
##  1st Qu.: 44.75   1st Qu.: 4.75   1st Qu.:1.00   WD15   :16  
##  Median : 88.50   Median : 8.50   Median :1.50   WD22   :16  
##  Mean   : 88.50   Mean   : 8.50   Mean   :1.75   WD29   :16  
##  3rd Qu.:132.25   3rd Qu.:12.25   3rd Qu.:2.25   WD36   :16  
##  Max.   :176.00   Max.   :16.00   Max.   :3.00   WD43   :16  
##                                                  (Other):80  
##      Weight           Time      
##  Min.   :225.0   Min.   : 1.00  
##  1st Qu.:267.0   1st Qu.:15.00  
##  Median :344.5   Median :36.00  
##  Mean   :384.5   Mean   :33.55  
##  3rd Qu.:511.2   3rd Qu.:50.00  
##  Max.   :628.0   Max.   :64.00  
## 

First plotting the weights of the 16 rats with three different nutrition during 11 weeks.

RATSL$ID <- factor(RATSL$ID)
RATSL$Group <- factor(RATSL$Group)
ggplot(RATSL, aes(x = Time, y = Weight, linetype = ID)) +
  geom_line() +
  scale_linetype_manual(values = rep(1:10, times=4)) +
  facet_grid(. ~ Group, labeller = label_both) +
  theme(legend.position = "none") + 
  scale_y_continuous(limits = c(min(RATSL$Weight), max(RATSL$Weight)))

In the picture we can see first of all that the weight of every rat has grown through the weeks and in the groups two and three it seems like the bigger the rat has been in the beginning, the bigger it is also in the end. There is clearly a difference between the group 1 and the other groups but we cant be sure why is that because rats in the first group have been smaller in the beginning. In group one the growth seems to be quite steady. Also the variability seems to stay quite steady during the time period in every group but some differences occur among the rats but there cant really be seen clear differences between the groups. Lets see if standardizing the data helps us with that.

Standardized data

RATSL <- RATSL %>%
  group_by(Time) %>%
  mutate(stdratsl = (Weight - mean(Weight))/sd(Weight) ) %>%
  ungroup()
ggplot(RATSL, aes(x = Time, y = stdratsl, linetype = ID)) +
  geom_line() +
  scale_linetype_manual(values = rep(1:10, times=4)) +
  facet_grid(. ~ Group, labeller = label_both) +
  scale_y_continuous(name = "standardized bprs")

Here we can see, that some of the weight curves seems to be downward. Over all no clear trends can be seen.

Summary measure analysis

n <- RATSL$Time %>% unique() %>% length()
RATSS <- RATSL %>%
  group_by(Group, Time) %>%
  summarise( mean = mean(Weight), se = sd(Weight)/ sqrt(n) ) %>%
  ungroup()
glimpse(RATSS)
## Observations: 33
## Variables: 4
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,...
## $ Time  <int> 1, 8, 15, 22, 29, 36, 43, 44, 50, 57, 64, 1, 8, 15, 22, ...
## $ mean  <dbl> 250.625, 255.000, 254.375, 261.875, 264.625, 265.000, 26...
## $ se    <dbl> 4.589478, 3.947710, 3.460116, 4.100800, 3.333956, 3.5529...
ggplot(RATSS, aes(x = Time, y = mean, linetype = Group, shape = Group)) +
  geom_line() +
  scale_linetype_manual(values = c(1,2,3)) +
  geom_point(size=3) +
  scale_shape_manual(values = c(1,2,3)) +
  geom_errorbar(aes(ymin=mean-se, ymax=mean+se, linetype="1"), width=0.3) +
  theme(legend.position = c(0.8,0.8,0.8)) +
  scale_y_continuous(name = "mean(Weight) +/- se(Weight)")
## Warning in if (position != "none") {: the condition has length > 1 and only
## the first element will be used
## Warning in if (position == "manual") {: the condition has length > 1 and
## only the first element will be used
## Warning in if (position == "left") {: the condition has length > 1 and only
## the first element will be used
## Warning in if (position == "right") {: the condition has length > 1 and
## only the first element will be used
## Warning in if (position == "bottom") {: the condition has length > 1 and
## only the first element will be used
## Warning in if (position == "top") {: the condition has length > 1 and only
## the first element will be used
## Warning in if (position == "manual") {: the condition has length > 1 and
## only the first element will be used

The summary measure method captures the variability of each observation, ie. the variability of the weight of each rat during the timepoints and now we can see, that there is not a difference between the groups two and three. Group one seems to differ from the other groups.

Boxplots and outliers

RATSL8S <- RATSL %>%
  filter(Time > 0) %>%
  group_by(Group, ID) %>%
  summarise( mean=mean(Weight) ) %>%
  ungroup()
glimpse(RATSL8S)
## Observations: 16
## Variables: 3
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3
## $ ID    <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
## $ mean  <dbl> 261.0909, 237.6364, 260.1818, 266.5455, 269.4545, 274.72...
ggplot(RATSL8S, aes(x = Group, y = mean)) +
  geom_boxplot() +
  stat_summary(fun.y = "mean", geom = "point", shape=23, size=4, fill = "white") +
  scale_y_continuous(name = "mean(Time), WD 1-11")

RATSL8S1 <- RATSL8S %>%
  filter(mean < 550)
ggplot(RATSL8S1, aes(x = Group, y = mean)) +
  geom_boxplot() +
  stat_summary(fun.y = "mean", geom = "point", shape=23, size=4, fill = "white") +
  scale_y_continuous(name = "mean(Time), WD 1-11")

Here we have two boxplots; the first one showing the outlier in the data in group two, witch was actually quite clearly seen in the previous pictures as well. When removing the outlier, we can see that the variability seems to be smaller in group three than group two witch still doesnt have to mean that there is differences between the nutritions. In group one theres nothing new revealed here. To get closer to the truth about the diffeences between the groups, we will see how regression model works.

RATS <- read.table("https://raw.githubusercontent.com/KimmoVehkalahti/MABS/master/Examples/data/rats.txt", header = TRUE, sep = '\t')
RATSL8S2 <- RATSL8S %>%
  mutate(baseline = RATS$WD1)
fit <- lm(formula (mean ~ RATS$WD1 + Group), data = RATSL8S2)
summary(fit)
## 
## Call:
## lm(formula = formula(mean ~ RATS$WD1 + Group), data = RATSL8S2)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -21.732  -3.812   1.991   6.889  13.455 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 30.14886   19.88779   1.516   0.1554    
## RATS$WD1     0.93194    0.07793  11.959 5.02e-08 ***
## Group2      31.68866   17.11189   1.852   0.0888 .  
## Group3      21.52296   21.13931   1.018   0.3287    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 10.62 on 12 degrees of freedom
## Multiple R-squared:  0.9947, Adjusted R-squared:  0.9933 
## F-statistic: 747.8 on 3 and 12 DF,  p-value: 6.636e-14

Here we can see that there are no significant differences between the nutrition groups, but the weight in the beginnig is a statistically significant predictor.

Linear mixed effects models for normal response variables with the BPRSL data

BPRSL <-read.csv("create_BPRSL.csv", TRUE, ",")
dim(BPRSL)
## [1] 360   6
str(BPRSL)
## 'data.frame':    360 obs. of  6 variables:
##  $ X        : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ treatment: int  1 1 1 1 1 1 1 1 1 1 ...
##  $ subject  : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ weeks    : Factor w/ 9 levels "week0","week1",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ bprs     : int  42 58 54 55 72 48 71 30 41 57 ...
##  $ week     : int  0 0 0 0 0 0 0 0 0 0 ...
summary(BPRSL)
##        X            treatment      subject          weeks    
##  Min.   :  1.00   Min.   :1.0   Min.   : 1.00   week0  : 40  
##  1st Qu.: 90.75   1st Qu.:1.0   1st Qu.: 5.75   week1  : 40  
##  Median :180.50   Median :1.5   Median :10.50   week2  : 40  
##  Mean   :180.50   Mean   :1.5   Mean   :10.50   week3  : 40  
##  3rd Qu.:270.25   3rd Qu.:2.0   3rd Qu.:15.25   week4  : 40  
##  Max.   :360.00   Max.   :2.0   Max.   :20.00   week5  : 40  
##                                                 (Other):120  
##       bprs            week  
##  Min.   :18.00   Min.   :0  
##  1st Qu.:27.00   1st Qu.:2  
##  Median :35.00   Median :4  
##  Mean   :37.66   Mean   :4  
##  3rd Qu.:43.00   3rd Qu.:6  
##  Max.   :95.00   Max.   :8  
## 
BPRSL$treatment <- factor(BPRSL$treatment)
BPRSL$subject <- factor(BPRSL$subject)

Plotting the BPRSL data

dim(BPRSL)
## [1] 360   6
ggplot(BPRSL, aes(x = week, y = bprs, group = treatment)) +
  geom_line() + aes(linetype = treatment) + scale_x_continuous(name = "week (weeks)", breaks = seq(0, 60, 10)) + scale_y_continuous(name = "treatment (points)") + theme(legend.position = "top")

BPRS_reg <- lm(formula = bprs ~ week + treatment, data = BPRSL)
summary(BPRS_reg)
## 
## Call:
## lm(formula = bprs ~ week + treatment, data = BPRSL)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -22.454  -8.965  -3.196   7.002  50.244 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  46.4539     1.3670  33.982   <2e-16 ***
## week         -2.2704     0.2524  -8.995   <2e-16 ***
## treatment2    0.5722     1.3034   0.439    0.661    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 12.37 on 357 degrees of freedom
## Multiple R-squared:  0.1851, Adjusted R-squared:  0.1806 
## F-statistic: 40.55 on 2 and 357 DF,  p-value: < 2.2e-16

In this plot it seems that there are some differencies between the treatment groups, but in the regression model the treatmentgroups dont differ with statistical significance. The flowing time/weeks instead seems to have a statistically significant meaning to the overall decreasing symptoms. The only problem here is that here we concider the variables as independent, witch is FALSE, so this really isnt the truth yet.

Fitting a random intercept model

BPRS_ref <- lmer(bprs ~ week + treatment + (1 | subject), data = BPRSL, REML = FALSE)
summary(BPRS_ref)
## Linear mixed model fit by maximum likelihood  ['lmerMod']
## Formula: bprs ~ week + treatment + (1 | subject)
##    Data: BPRSL
## 
##      AIC      BIC   logLik deviance df.resid 
##   2748.7   2768.1  -1369.4   2738.7      355 
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -3.0481 -0.6749 -0.1361  0.4813  3.4855 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev.
##  subject  (Intercept)  47.41    6.885  
##  Residual             104.21   10.208  
## Number of obs: 360, groups:  subject, 20
## 
## Fixed effects:
##             Estimate Std. Error t value
## (Intercept)  46.4539     1.9090  24.334
## week         -2.2704     0.2084 -10.896
## treatment2    0.5722     1.0761   0.532
## 
## Correlation of Fixed Effects:
##            (Intr) week  
## week       -0.437       
## treatment2 -0.282  0.000

In this case there isnt any significant differences between the values in the model where we considered the variables independent and this with random intercept.

Random intercept and random slope model

BPRS_ref1 <- lmer(bprs ~ week + treatment + (week | subject), data = BPRSL, REML = FALSE)
summary(BPRS_ref1)
## Linear mixed model fit by maximum likelihood  ['lmerMod']
## Formula: bprs ~ week + treatment + (week | subject)
##    Data: BPRSL
## 
##      AIC      BIC   logLik deviance df.resid 
##   2745.4   2772.6  -1365.7   2731.4      353 
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -2.8919 -0.6194 -0.0691  0.5531  3.7977 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev. Corr 
##  subject  (Intercept) 64.8222  8.0512        
##           week         0.9609  0.9803   -0.51
##  Residual             97.4304  9.8707        
## Number of obs: 360, groups:  subject, 20
## 
## Fixed effects:
##             Estimate Std. Error t value
## (Intercept)  46.4539     2.1052  22.066
## week         -2.2704     0.2977  -7.626
## treatment2    0.5722     1.0405   0.550
## 
## Correlation of Fixed Effects:
##            (Intr) week  
## week       -0.582       
## treatment2 -0.247  0.000
anova(BPRS_ref1, BPRS_ref)
## Data: BPRSL
## Models:
## BPRS_ref: bprs ~ week + treatment + (1 | subject)
## BPRS_ref1: bprs ~ week + treatment + (week | subject)
##           Df    AIC    BIC  logLik deviance  Chisq Chi Df Pr(>Chisq)  
## BPRS_ref   5 2748.7 2768.1 -1369.4   2738.7                           
## BPRS_ref1  7 2745.4 2772.6 -1365.7   2731.4 7.2721      2    0.02636 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

These values are also very similar to the random intercept model, but the chi-square gives this model better fit with statistical significance.

Random intercept and random slope model with interaction

BPRS_ref2 <- lmer(bprs ~ week * treatment + ( week| subject), data = BPRSL, REML = FALSE)
summary(BPRS_ref2)
## Linear mixed model fit by maximum likelihood  ['lmerMod']
## Formula: bprs ~ week * treatment + (week | subject)
##    Data: BPRSL
## 
##      AIC      BIC   logLik deviance df.resid 
##   2744.3   2775.4  -1364.1   2728.3      352 
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -3.0512 -0.6271 -0.0768  0.5288  3.9260 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev. Corr 
##  subject  (Intercept) 64.9964  8.0620        
##           week         0.9687  0.9842   -0.51
##  Residual             96.4707  9.8220        
## Number of obs: 360, groups:  subject, 20
## 
## Fixed effects:
##                 Estimate Std. Error t value
## (Intercept)      47.8856     2.2521  21.262
## week             -2.6283     0.3589  -7.323
## treatment2       -2.2911     1.9090  -1.200
## week:treatment2   0.7158     0.4010   1.785
## 
## Correlation of Fixed Effects:
##             (Intr) week   trtmn2
## week        -0.650              
## treatment2  -0.424  0.469       
## wek:trtmnt2  0.356 -0.559 -0.840
anova(BPRS_ref2, BPRS_ref1)
## Data: BPRSL
## Models:
## BPRS_ref1: bprs ~ week + treatment + (week | subject)
## BPRS_ref2: bprs ~ week * treatment + (week | subject)
##           Df    AIC    BIC  logLik deviance  Chisq Chi Df Pr(>Chisq)  
## BPRS_ref1  7 2745.4 2772.6 -1365.7   2731.4                           
## BPRS_ref2  8 2744.3 2775.4 -1364.1   2728.3 3.1712      1    0.07495 .
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Fitted <- fitted(BPRS_ref2)
BPRSL <- BPRSL %>%
  mutate(Fitted)